package com.galangel.bookservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.galangel.bookservice.domain.dto.AddShopcar;
import com.galangel.bookservice.domain.pojo.BookCopy;
import com.galangel.bookservice.domain.pojo.BookInfo;
import com.galangel.bookservice.domain.vo.ShopcarVo;
import com.galangel.bookservice.entity.Shopcar;
import com.galangel.bookservice.service.IBookCopyService;
import com.galangel.bookservice.service.IBookInfoService;
import com.galangel.bookservice.service.IShopcarService;
import com.galangel.bookservice.service.IUserService;
import com.galangel.common.domain.R;
import com.galangel.common.utils.BeanUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author galangel
 * @since 2025-06-17
 */
@RestController
@RequestMapping("/shopcar")
@RequiredArgsConstructor
public class ShopcarController {
    final private IShopcarService shopcarService;
    final private IUserService userService;
    final private IBookInfoService bookInfoService;
    final private IBookCopyService bookCopyService;

    @PostMapping("/add")
    public R addShopcar(@RequestBody Shopcar shopcar){
        return R.ok(shopcarService.save(shopcar));
    }

    @GetMapping("/{username}/{isbn}")
    public R findShopcar(@PathVariable String username, @PathVariable String isbn){
        return R.ok(shopcarService.getOne(
                new QueryWrapper<Shopcar>()
                        .eq("username", username)
                        .eq("isbn", isbn)
        ));
    }

    @DeleteMapping("/{username}/{isbn}")
    public R deleteShopcar(@PathVariable String username, @PathVariable String isbn){
        return R.ok(shopcarService.remove(
                new QueryWrapper<Shopcar>()
                        .eq("username", username)
                        .eq("isbn", isbn)
        ));
    }

    @GetMapping("/{username}")
    public R findShopcar(@PathVariable String username){
        List<Shopcar> shopcars = shopcarService.list(
                new QueryWrapper<Shopcar>()
                        .eq("username", username)
        );
        List<ShopcarVo> shopcarVos = new ArrayList<>();

        for (Shopcar shopcar : shopcars) {
            ShopcarVo shopcarVo = new ShopcarVo();
            BeanUtils.copyProperties(shopcar, shopcarVo);
            BookInfo info = bookInfoService.getOne(new QueryWrapper<BookInfo>().eq("isbn", shopcar.getIsbn()));
            BeanUtils.copyProperties(info, shopcarVo);
            BookCopy bookCopy = bookCopyService.getOne(new QueryWrapper<BookCopy>().eq("isbn", shopcar.getIsbn()));
            BeanUtils.copyProperties(bookCopy, shopcarVo);
            shopcarVos.add(shopcarVo);
        }
        return R.ok(shopcarVos);
    }

}
